package middleware

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"time"
	"xialou_platform/app/errorx"
	"xialou_platform/app/jwtx"
	"xialou_platform/app/middleware/model"

	"github.com/bwmarrin/snowflake"
	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/rest/httpx"
	"golang.org/x/net/context"
)

type OperationLogMiddleware struct {
	operationLogModel model.OperationLogModel
	secret            string
	flake             *snowflake.Node
}

func NewOperationLogMiddleware(operationLogModel model.OperationLogModel, secret string) *OperationLogMiddleware {
	flake, _ := snowflake.NewNode(20)
	return &OperationLogMiddleware{
		operationLogModel: operationLogModel,
		secret:            secret,
		flake:             flake,
	}
}
func (m *OperationLogMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		authorization := r.Header.Get("Authorization")

		//if m.jwtModel.IsBlack(r.Context(), authorization) {
		//	unauthorized(w, r, errorx.NewErrMsg("Login Expire"))
		//	return
		//}
		ctx := r.Context()
		if len(authorization) > 0 {
			var claim jwtx.MyClaims
			tok, err := jwt.ParseWithClaims(authorization, &claim, func(token *jwt.Token) (interface{}, error) {
				return []byte(m.secret), nil
			})
			if err != nil {
				httpx.WriteJson(w, http.StatusBadRequest,
					errorx.NewMsgCodeError(errorx.UnLoginCode, "请登录"))
			}
			if !tok.Valid {
				httpx.WriteJson(w, http.StatusBadRequest,
					errorx.NewMsgCodeError(errorx.UnLoginCode, "请登录"))
			}
			param, err := ioutil.ReadAll(r.Body)
			r.Body = ioutil.NopCloser(bytes.NewBuffer(param))

			_, err = m.operationLogModel.Insert(ctx, &model.OperationLog{
				Id:         m.flake.Generate().Int64(),
				Uid:        claim.Uid,
				CreateTime: time.Now(),
				Url:        r.RequestURI,
				Param:      string(param),
			})
			if err != nil {

			}
			ctx = context.WithValue(ctx, "uid", claim.Uid)
			next(w, r.WithContext(ctx))
		} else {
			httpx.WriteJson(w, http.StatusBadRequest,
				errorx.NewMsgCodeError(errorx.UnLoginCode, "请登录"))

		}
	}
}
